package zhouzhouyongche.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import zhouzhouyongche.client_util.ClientOrder;
import zhouzhouyongche.client_util.ErrorCode;
import zhouzhouyongche.dao.OrderDao;
import zhouzhouyongche.dao.PassengerDao;
import zhouzhouyongche.dao.SeatDao;
import zhouzhouyongche.dao.TicketDao;
import zhouzhouyongche.dao.UserDao;
import zhouzhouyongche.model.Order;
import zhouzhouyongche.model.Passenger;
import zhouzhouyongche.model.Seat;
import zhouzhouyongche.model.Ticket;
import zhouzhouyongche.model.User;
import zhouzhouyongche.service.OrderService;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderDao orderDao;
	@Autowired
	private TicketDao ticketDao;
	@Autowired
	private PassengerDao passengerDao;
	@Autowired
	private SeatDao seatDao;
	@Autowired
	private UserDao userDao;
	
	@Override
	public int saveOrder(int userId, int passengerId, int ticketId, int seatNumber, int ticketPickerId, String phoneNumberOfTicketPicker) {
		boolean res = true;
		Order order = new Order();
		Ticket ticket = ticketDao.get(ticketId);
		Passenger passenger = passengerDao.get(passengerId);
		Passenger passengerTicketPicker = passengerDao.get(ticketPickerId);
		User user = userDao.get(userId);
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		
		order.setOrderCode(String.valueOf(calendar.getTimeInMillis()));
		order.setStartCity(ticket.getStartCity());
		order.setStartPassengerStation(ticket.getStartPassengerStation());
		order.setEndCity(ticket.getEndCity());
		order.setYear(ticket.getYear());
		order.setMonth(ticket.getMonth());
		order.setDay(ticket.getDay());
		order.setHour(ticket.getHour());
		order.setMinute(ticket.getMinute());
		order.setPassenger(passenger);
		order.setPrice(ticket.getPrice());
		order.setStatus(0);
		order.setPhoneNumberOfTicketPicker(phoneNumberOfTicketPicker);
		order.setTicketPicker(passengerTicketPicker);
		order.setBusType(ticket.getBusType());
		order.setEndSite(ticket.getEndSite());
		
		user.getOrders().add(order);
		
		//1.Ticket表库存减1
		ticket.setInventory(ticket.getInventory() - 1);
		
		//2.插入Seat表，表示相应座位已经被预订
		Seat seat = new Seat();
		seat.setSeatNumber(seatNumber);
		ticket.getSeats().add(seat);
		
		SessionFactory sessionFactory = null;
		Session session = null;
		Transaction tx = null;
		
		try {			
			sessionFactory = orderDao.getSessionFactory();
			session = sessionFactory.openSession();
			tx = session.beginTransaction();
			
			seatDao.save(seat);
			ticketDao.update(ticket);
			orderDao.save(order);
			userDao.save(user);
			
			tx.commit();
		} catch(Exception e) {
			e.printStackTrace();
			if (tx != null) 
				tx.rollback();
			res = false;
		} finally {
			session.close();
		}
		return res ? ErrorCode.SUCCESS : ErrorCode.ERROR_SEAT_BOOKED;
	}

	@Override
	public void cancelOrder(String orderCode) {
		orderDao.cancelOrder(orderCode);
	}

	@Override
	public List<ClientOrder> getOrders(int userId) {
		List<Order> orders = orderDao.getOrders(userId);
		return transform(orders);
	}

	private List<ClientOrder> transform(List<Order> orders) {
		List<ClientOrder> clientOrders = new ArrayList<ClientOrder>();
		for (int i = 0; i < orders.size(); i++) {
			ClientOrder clientOrder = new ClientOrder();
			Order order = orders.get(i);
			
			clientOrder.setDay(order.getDay().getDay());
			clientOrder.setEndCityName(order.getEndCity().getCityName());
			clientOrder.setMonth(order.getMonth().getMonth());
			clientOrder.setOrderCode(order.getOrderCode());
			clientOrder.setPassengerName(order.getPassenger().getPassengerName());
			clientOrder.setPrice(order.getPrice());
			clientOrder.setStartCityName(order.getStartCity().getCityName());
			clientOrder.setStartPassengerStationName(order.getStartPassengerStation().getPassengerStationName());
			clientOrder.setStatus(order.getStatus());
			clientOrder.setYear(order.getYear().getYear());
			clientOrder.setBusType(order.getBusType());
			clientOrder.setHour(order.getHour().getHour());
			clientOrder.setMinute(order.getMinute().getMinute());
			clientOrder.setEndSiteName(order.getEndSite().getSiteName());
			clientOrder.setTicketPicker(order.getTicketPicker().getPassengerName());
			
			clientOrders.add(clientOrder);
		}
		return clientOrders;
	}
}
